package org.thanos.demo.util;

import org.springframework.context.ApplicationContext;
import org.springframework.util.Assert;


public class SpringUtil {

    private static ApplicationContext context;

    private SpringUtil() {
        super();
    }

    public static void inject(ApplicationContext ctx) {
        context = ctx;
    }

    public static <T> T getBean(Class<T> clz) {
        Assert.notNull(context, "context may not be injected");
        return context.getBean(clz);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String className) throws ClassNotFoundException {
        Assert.notNull(context, "context may not be injected");
        // 1. ClassLoader 存在，则直接使用 clz 加载
        ClassLoader classLoader = context.getClassLoader();
        if (classLoader != null) {
            return (T) context.getBean(classLoader.loadClass(className));
        }
        // 2. ClassLoader 不存在(系统类加载器不可见)，尝试用类名称小写加载
        String[] split = className.split("\\.");
        String beanName = split[split.length - 1];
        // 小写转大写
        char[] cs = beanName.toCharArray();
        cs[0] += 32;
        return (T) context.getBean(String.valueOf(cs));
    }
}
